package srv

import (
	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
)

// Dictionary 字典表管理
type Dictionary struct {
	DictionaryBll *bll.Dictionary `inject:""`
}

// QueryPage 查询分页数据
func (a *Dictionary) QueryPage(ctx *context.Context) error {
	pageIndex, pageSize := ctx.GetPageIndex(), ctx.GetPageSize()

	params := schema.DictionaryQueryParam{
		Name:     ctx.Query("name"),
		ParentID: ctx.Query("parent_id"),
	}

	total, items, err := a.DictionaryBll.QueryPage(params, pageIndex, pageSize)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}

	result := map[string]interface{}{
		"list": items,
		"pagination": map[string]interface{}{
			"total":    total,
			"current":  pageIndex,
			"pageSize": pageSize,
		},
	}

	return ctx.ResSuccess(result)
}

// QueryTree 查询树形数据
func (a *Dictionary) QueryTree(ctx *context.Context) error {
	var (
		root  string
		level int
		items []map[string]interface{}
		err   error
	)
	root = ctx.Query("root")
	level = ctx.QueryInt("level")

	items, err = a.DictionaryBll.QueryTree(root, level)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// QueryShowTree 查询树形数据展示
func (a *Dictionary) QueryShowTree(ctx *context.Context) error {
	var (
		root  string
		level int
		items []map[string]interface{}
		err   error
	)
	root = ctx.Query("root")
	level = ctx.QueryInt("level")

	items, err = a.DictionaryBll.QueryTree(root, level, true)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// QueryNameList 查询字典名列表
func (a *Dictionary) QueryNameList(ctx *context.Context) error {
	var (
		list  []string
		root  string
		items []map[string]interface{}
		err   error
	)
	root = ctx.Query("root")
	list = ctx.QueryList("code")
	items, err = a.DictionaryBll.QueryTree(root, 1, true)
	if err != nil {
		return ctx.ResErrBadRequest(err)
	}
	if len(list) > 0 {
		for i, v := range list {
			list[i] = ""
			for _, m := range items {
				if m["code"] == v {
					list[i] = m["name"].(string)
					break
				}
			}
		}
	} else {
		for _, m := range items {
			list = append(list, m["name"].(string))
		}
	}
	return ctx.ResSuccess(list)
}

// GetByCode 根据Code获取名字
func (a *Dictionary) GetByCode(ctx *context.Context) error {
	var (
		item *schema.Dictionary
		err  error
		name string
	)
	item, err = a.DictionaryBll.GetByCode(ctx.Query("code"))
	if err != nil {
		return ctx.ResErrBadRequest(err)
	}
	name = item.Name
	return ctx.ResSuccess(name)
}
